from django.db.models import ImageField
from django.db.models.fields.files import ImageFieldFile
from django.core.files.base import ContentFile
from PIL import Image
import cStringIO

def create_thumb(img, thumb_size, format):
    print "Starting thumb creation"
    
    img.seek(0) # see http://code.djangoproject.com/ticket/8222 for details

    image = Image.open(img)
    
    # convert to rgb
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
        
    # get thumbnail sizes
    thumb_w, thumb_h = thumb_size
    
    
    if thumb_w == thumb_h:
        print "Creating square thumb"
        # square thumbnail    
        # get image dimensions
        xsize, ysize = image.size
    
        minsize = min(xsize, ysize)
        
        # find biggest square in the image. this helps for cropping
        xnewsize = (xsize - minsize)/2
        ynewsize = (ysize - minsize)/2
        
        # crop coordinates: left, up, right, down.
        #
        #   0----Xmax
        #   |       |
        #   |       |
        #   |       |
        #   Ymax----|
        
        image = image.crop((xnewsize, ynewsize, xsize - xnewsize, ysize - ynewsize))
        image.thumbnail(thumb_size, Image.ANTIALIAS)
    
    else:
        print "Non square thumb"
        # not square thumbnail
        image.thumbnail(thumb_size, Image.ANTIALIAS)
    
    io = cStringIO.StringIO()
    
    # make the format uppercase for consistency
    format = format.upper()
    
    # PNG, GIF are the same as their extension, JPG is JPEG
    if format == 'JPG':
        format = 'JPEG'

    image.save(io,format)
    
    print "Ending thumb creation. Returning object."
    return ContentFile(io.getvalue())
    

class ImageAndThumbFieldFile(ImageFieldFile):
    def __init__(self, *args, **kwargs):
        super(ImageAndThumbFieldFile, self).__init__(*args, **kwargs)
        self.th_size = self.field.th_size
        
        def _get_thumb_url(self):
            if not self:
                return ''
            else:
                # split the extension
                split = self.url.rsplit('.',1)
                
                # add '_th' between filename and extension
                thumb_url = '%s_th.%s' % (split[0],split[1])
                
                return thumb_url
            
        setattr(self, 'thumb_url',_get_thumb_url(self))

        def _get_thumb_path(self):
            if not self:
                return ''
            else:
                # split the extension
                split = self.path.rsplit('.',1)
                
                # add '_th' between filename and extension
                thumb_path = '%s_th.%s' % (split[0],split[1])
                
                return thumb_path
            
        setattr(self, 'thumb_path',_get_thumb_path(self))

    def save(self, name, content, save = True):
        super(ImageAndThumbFieldFile, self).save(name,content,save)
        
        # split[0] = filename without extension, split[1] = extension
        split = self._name.rsplit('.',1)
        
        thumb_name = '%s_th.%s' % (split[0],split[1])
        
        thumb_content = create_thumb(content, self.th_size, split[1])
        
        thumb_name_ = self.storage.save(thumb_name, thumb_content)
        
        if not thumb_name == thumb_name_:
            raise ValueError('There is already a file named %s' % thumb_name)
        
                
    def delete(self, save = True):
        name = self.name
        super(ImageAndThumbFieldFile, self).delete(save)
        
        split = name.rsplit('.',1)
        thumb_name = '%s_th.%s' % (split[0],split[1])
        try:
            self.storage.delete(thumb_name)
        except:
            pass
        

class ImageAndThumbField(ImageField):
    attr_class = ImageAndThumbFieldFile
    
    def __init__(self, verbose_name = None, name = None, width_field = None, height_field = None, th_size = (70,70), **kwargs):
        self.verbose_name = verbose_name
        self.name = name
        self.width_field = width_field
        self.height_field = height_field
        self.th_size = th_size
        super(ImageField, self).__init__(**kwargs)
            
                